package com.blog.service;

import com.blog.dao.CategoryMapper;
import com.blog.dao.NewsMapper;
import com.blog.model.Category;
import com.github.pagehelper.PageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


@Service
public class CategoryService {

    @Resource
    protected CategoryMapper categoryMapper;

    @Resource
    private NewsMapper newsMapper;

    @Resource
    private HttpServletResponse response;

    public Category findOne(Integer id){
        Category data = categoryMapper.selectByPrimaryKey(id);
        return data;
    }

    public List<Category> findAll(Category category){
        if (category.getPage() != null && category.getRows() != null) {
            PageHelper.startPage(category.getPage(), category.getRows());
        }
        Example example = new Example(Category.class);
        Example.Criteria criteria = example.createCriteria();
        if (category.getName() != null && category.getName().length() > 0) {
            criteria.andLike("name", "%" + category.getName() + "%");
        }
        return categoryMapper.selectByExample(example);
    }

    public List<Category> selectAll(){
        List<Category> data = categoryMapper.findAll();
        return data;
    }

    public List<Category> selectAll(Category category){
        Example example = new Example(Category.class);
        Example.Criteria criteria = example.createCriteria();
        if (category.getName() != null && category.getName().length() > 0) {
            criteria.andLike("name", "%" + category.getName() + "%");
        }

        List<Category> data = categoryMapper.selectByExample(example);
        return data;
    }

    public void addCategory(Category category){
        categoryMapper.insertUseGeneratedKeys(category);
    }

    public void editCategory(Category category){
        categoryMapper.updateByPrimaryKeySelective(category);
    }

    public void deleteCategory(Integer id){
        categoryMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    public void test(Category category){
        categoryMapper.insertUseGeneratedKeys(category);
        category.setId(27);
        categoryMapper.insertUseGeneratedKeys(category);
    }


    /*统计分类下文章的数量*/
    @Async
    public void countCategory() {
        List<Category> list = categoryMapper.findAll();
        for(Category cate:list){
            Integer catid = cate.getId();
            int num = newsMapper.getNewsCount(catid);
//            News newsObj = new News();
//            newsObj.setCateid(catid);
//            int count = newsMapper.selectCount(newsObj);
            cate.setCount(num);
            categoryMapper.updateByPrimaryKeySelective(cate);
        }
    }
}
